<template>
  <view class="create-product h-full flex flex-col box-border">
    <view class="position-relative h-520rpx">

      <template v-if="swiperList.length">
        <u-swiper :height="260" :list="swiperList" :current="swiperCurr" indicator indicatorMode="dot" circular
          :autoplay="false"></u-swiper>
        <view class="position-absolute top-20rpx right-15rpx flex" v-if="!oriImg.length">
          <view class="swiper-icon">
            <up-icon name="trash-fill" size="24" color="#fff" @click="delImg"></up-icon>
          </view>
          <up-upload :fileList="fileList" name="files" multiple :maxCount="5 - swiperList.length"
            :maxSize="10 * 1024 * 1024" :uploadText="`可上传${5 - fileList.length}张图片`" :previewImage="false"
            @oversize="beforeRead" @afterRead="afterRead" @delete="deletePic">
            <view class="swiper-icon" v-if="swiperList.length < 5">
              <up-icon name="plus" size="24" color="#fff"></up-icon>
            </view>
          </up-upload>
        </view>
      </template>
      <up-upload :fileList="fileList" name="files" multiple :maxCount="5 - swiperList.length"
        :maxSize="10 * 1024 * 1024" :uploadText="`可上传${5 - fileList.length}张图片`" :previewImage="false"
        @oversize="beforeRead" @afterRead="afterRead" @delete="deletePic">
        <view v-if="!swiperList.length" class="flex flex-col justify-center items-center bg-#F4F4F4 color-#919191"
          style="height: 520rpx;width: 100vw;">
          <image style="width:116rpx;height: 116rpx;" src="../../assets/images/upload.png" />
          <text>点击上传产品图片</text>
        </view>
      </up-upload>

    </view>
    <view class="flex-1 bg-#F9FAFB p-16rpx position-relative" style="min-height: 0;">
      <view class="font-bold font-size-32rpx">
        {{ currentRecord.description }}
      </view>
      <view calss="bg-#ffffff m-b-20rpx" style="margin: 0 20rpx;background-color: #fff;">
        <u-cell-group calss="bg-#ffffff" :border="false">
          <u-cell calss="bg-#ffffff" title="需求数量" :value="currentRecord.demandCount + currentRecord.unit"></u-cell>
          <u-cell calss="bg-#ffffff" title="咨询时间" :value="currentRecord.askTime"></u-cell>
        </u-cell-group>
      </view>
      <view class="bg-#ffffff overflow-auto flex-1 p-32rpx text-28rpx" style="min-height: 0;">
        <up-form :labelWidth="200" class="create-product-card-info" :rules="rules" labelPosition="top" :model="formData"
          ref="infoFormRef">
          <up-form-item label="" prop="deliveryType">
            <up-radio-group v-model="formData.deliveryType" placement="row" @change="typeChange">
              <up-radio :customStyle="{ marginBottom: '8px' }" :key="1" label="预计货期" :name="1">
              </up-radio>
              <up-radio :customStyle="{ marginLeft: '10px', marginBottom: '8px' }" :key="2" label="现货" :name="2">
              </up-radio>
              <up-radio :customStyle="{ marginLeft: '10px', marginBottom: '8px' }" :key="3" label="无货" :name="3">
              </up-radio>
            </up-radio-group>
          </up-form-item>
          <up-form-item v-if="formData.deliveryType === 1" label="预计货期（天）" prop="deliveryDay">
            <up-input type="text" :disabled="currentRecord.replyState || formData.deliveryType !== 1"
              v-model="formData.deliveryDay" :placeholder="currentRecord.replyState !== 1 ? '仅允许输入正整数' : ''"></up-input>
          </up-form-item>
          <up-form-item labelPosition="top" label="备注说明（选填）" prop="replyMessage">
            <u--textarea :disabled="currentRecord.replyState === 1" v-model="formData.replyMessage" count
              :maxlength="200" placeholder="请输入备注说明"></u--textarea>
          </up-form-item>
        </up-form>
      </view>
      <view v-if="currentRecord.replyState === 0"
        class="foot-card flex justify-center items-center w-full h-144rpx p-32rpx box-border"
        style="position: sticky;bottom: 0;">
        <up-button :disabled="!formData.deliveryDay" color="#1A5FA9" type="primary" shape="circle" text="回复货期"
          @click="editProductSave()"></up-button>
      </view>

    </view>
  </view>
</template>

<script setup lang="ts">
import { productManageSupUpdateProductPrice } from '@/genapi/productManageSup'
import { debounce } from '@antfu/utils'
import { handleFile } from "@/api/request"
import { thousandSeparatFormat, deThousandSeparatFormat } from "@/utils/utils";
import { queryDeliveryAskDetail, replyDeliveryAsk } from '@/genapi/_delivery';

const infoFormRef = ref()
const detailId = ref<string>('')
const oemCode = ref<string[]>([])
const deleteImgIds = ref<any[]>([])
let productId = ''
const currentRecord = ref<any>({})
const disabledFlag = ref(false)
const fileList = ref([])
const uploadList = ref([])
const formData = reactive<any>({
  deliveryType: 1,
  deliveryDay: '',
  replyMessage: '',
  files: [] as any,
})
const swiperList = ref([])
const oriImg = ref<any>([])
const uploadImg = ref<any>([])
const swiperCurr = ref(0)

watch(() => uploadList.value, (val) => {
  console.log(val)
  if (val.length) {
    let boo = val.every(item => item)
    if (boo) {
      uploadList.value.length = 0
      uni.hideLoading()
    }
  } else {
    uni.hideLoading()
  }
}, { deep: true })

const rules = reactive({
  deliveryDay: {
    required: true,
    validator: (rule: any, value: string, cb: (str?: string) => void) => {
      if (formData.deliveryType !== 1) {
        cb()
      } else if (!formData.deliveryDay) { cb('请输入预计货期') }
      else if (!/^\d+$/.test(formData.deliveryDay)) { cb('仅允许输入正整数') }
      else if ((+formData.deliveryDay < 1 || +formData.deliveryDay > 730)) {
        cb('货期必须在1-730天之间')
      }
      else {
        cb()
      }
    },
    trigger: ['change', 'blur']
  },
  // files:
  // {
  //   validator: (rule: any, value: any, cb: (val?: any) => void) => {
  //     const oemArr = oemCode.value.slice()
  //     if (!fileList.value.length && !oemArr.concat(currentRecord.value?.oemCodeList || [])) {
  //       cb(new Error('OEM号和图片至少传一个'))
  //     }
  //     else { cb() }
  //   },
  //   trigger: ['change', 'blur'],
  // }
})
function typeChange() {
  infoFormRef.value.clearValidate('deliveryDay')
  formData.deliveryDay = ''
  if (formData.deliveryType === 1) {
    formData.deliveryDay = formData.deliveryDay
  } else if (formData.deliveryType === 2) {
    formData.deliveryDay = '现货'
  } else {
    formData.deliveryDay = '无货'
  }
}
function beforeRead(a, b) {
  console.log(a, b)
  uni.showToast({
    title: '文件超出10MB,请检查',
    icon: 'none'
  })
}
function delImg() {
  console.log(swiperCurr.value)
  let delUrl = swiperList.value.splice(swiperCurr.value, 1)[0]
  if (delUrl) {
    let matchOne1 = oriImg.value.map(item => item.fileUrl).indexOf(delUrl)
    let matchOne2 = uploadImg.value.map(item => item.fileUrl).indexOf(delUrl)
    if (matchOne1 > -1) {
      oriImg.value.splice(matchOne1, 1)
    }
    if (matchOne2 > -1) {
      uploadImg.value.splice(matchOne2, 1)
      // fileList.value.splice(matchOne2, 1)
    }
    swiperList.value = [].concat(oriImg.value.map(item => item.fileUrl)).concat(uploadImg.value.map(item => item.fileUrl))
    swiperCurr.value = swiperList.value.length === swiperCurr.value ? 0 : swiperCurr.value
  }
}
// 删除文件
async function deletePic(res: any) {
  fileList.value.splice(res.index, 1)
  infoFormRef?.value?.validateField('files')
  infoFormRef?.value?.validateField('oemCode')
  if (res.file?.id) {
    deleteImgIds.value.push(res.file?.id)
  }
}
const uploadFilePromise = async (url: string) => {
  const uploadPromise = await new Promise(async (resolve, reject) => {
    await uni.uploadFile({
      url: `${import.meta.env.VITE_BASE_API_URL}/api/productManageSup/uploadProductFile`,
      filePath: url,
      name: 'file',
      header: {
        Authorization: 'Bearer ' + uni.getStorageSync('token')
      },
      formData: {
        id: currentRecord.value.id
      },
      success: (res) => {
        resolve(res.data || true)
      },
      fail: (res) => {
        uni.showToast({
          title: '上传失败！',
          icon: 'none'
        })
        reject(res)
      }
    })
    // await new Promise((resolve) => setTimeout(resolve, 800))
    // resolve(result)
  })
  return uploadPromise
}

// 保存成功回调
function successCalback() {
  infoFormRef?.value?.resetFields()
  infoFormRef?.value?.resetFields()
  uni.showToast({
    title: '保存成功',
    icon: 'success'
  })
  uni.switchTab({
    url: '/pages/index/index'
  })
}
async function afterRead(event: any) {
  console.log(event)
  if (event.file.length) {
    uni.showLoading({
      title: '加载中...'
    })
    // const photos: any = handleFile(event)
    // fileList.value = fileList.value.concat(photos)
    uploadList.value.length = event.file.length
    event.file.forEach((item: any, index) => {
      // uploadImg.value.push(item.url)

      uni.uploadFile({
        url: `${import.meta.env.VITE_BASE_API_URL}/api/deliveryAsk/uploadDeliveryAskImage`,
        filePath: item.url,
        name: 'file',
        header: {
          Authorization: 'Bearer ' + uni.getStorageSync('token')
        },
        success: (res) => {
          console.log(res)
          let data = JSON.parse(res.data)
          if (data.code === 200) {
            uploadImg.value.push(data.data)
            swiperList.value = [].concat(oriImg.value.map(item => item.fileUrl)).concat(uploadImg.value.map(item => item.fileUrl))
          }
          uploadList.value[index] = true
        },
        fail: (res) => {
          uploadList.value[index] = true
          uni.showToast({
            title: '上传失败！',
            icon: 'none'
          })
        }
        // ,complete:() => {
        //   uploadList.value[index] = true
        // }
      })
    })
  }
  // swiperList.value = [].concat(oriImg.value).concat(uploadImg.value)
  // if (fileList.value.length) {
  //   infoFormRef.value.clearValidate('oemCode')
  // }
}
async function askDelivery() {
  infoFormRef.value.validate().then(async (valid) => {
    if (valid) {
      const days = formData.deliveryType === 1 ? formData.deliveryDay : formData.deliveryType === 2 ? 0 : 999
      let params = {
        skuDeliveryAskId: detailId.value,
        deliveryType: formData.deliveryType,
        deliveryDay: days,
        replyMessage: formData.replyMessage,
        supFiles: uploadImg.value
      }
      const { data } = await replyDeliveryAsk(params)
      console.log(data.value)
      if (data?.code !== 200) {
        uni.showToast({
          title: data.msg,
          icon: 'none'
        })
      } else {
        uni.showToast({
          title: '回复成功',
          icon: 'success'
        })
        try {
          uni.navigateBack()
        } catch (error) {
          uni.reLaunch({
            url: '/pages/notifyManage/index'
          })
        }
      }
    }
  })
}
async function editProduct() {
  const isAddPicture = fileList.value.length && fileList.value.some(item => !(item?.id))
  Promise.all([infoFormRef.value.validate()]).then(async (results) => {
    const [vaild1] = results
    if (vaild1 === true) {
      let params: any = {}
      let priceArr = [...formData.priceList]
      priceArr = priceArr.map(item => {
        item.productPrice = deThousandSeparatFormat(item.productPrice)
        return item
      })
      // 已生成sku 保存商品信息，拿到id
      params = {
        id: productId,
        priceList: priceArr,
        applyOemCodeList: oemCode.value,
      }
      if (deleteImgIds.value.length) {
        params.deleteImgIds = deleteImgIds.value.join()
      }
      const { data } = await productManageSupUpdateProductPrice(params)
      if (data?.code === 200 && !isAddPicture) {
        successCalback()
      }
      if (data?.code !== 200 && data?.msg) {
        uni.showToast({
          title: data?.msg,
        })
        return
      }
      // 上传图片
      if (isAddPicture) {
        let newFiles = fileList.value.filter(e => !e.id) || []
        // 创建图片上传promise
        if (newFiles.length) {
          await Promise.all(newFiles.map(async (e) => {
            const promise = await uploadFilePromise(e.url)
            return promise
          })).then((results) => {
            const success = results.every(item => {
              item = JSON.parse(item)
              return item.code === 200
            })
            if (success) {
              successCalback()
            }
          }).catch((err: any) => {
            uni.showToast({
              title: '上传失败',
              icon: 'error'
            })
            console.error('上传失败:', err)
          })
        }
      }
    }
  })
    .catch((error) => {
      console.error('保存失败:', error);
    })
}
const editProductSave = debounce(500, askDelivery)
async function getProductDetail() {
  const { data } = await queryDeliveryAskDetail({ id: detailId.value })
  if (data?.code !== 200) return
  else {
    const result = data.data
    if (result.centerFirstImage)
      oriImg.value = [{ fileUrl: result.centerFirstImage, isOri: true }]
    currentRecord.value = result
    // swiperList.value = [].concat(oriImg.value).concat(uploadImg.value)
    swiperList.value = [].concat(oriImg.value.map(item => item.fileUrl)).concat(uploadImg.value.map(item => item.fileUrl))
    formData.deliveryType = result.deliveryType || 1
    // if (result.replyState) {
    //   if (result.deliveryType === 1)
    //     formData.deliveryDay = result.deliveryDay
    //   else if (result.deliveryType === 2)
    //     formData.deliveryDay = '现货'
    //   else
    //     formData.deliveryDay = '无货'
    // } else {
    //   formData.deliveryDay = result.deliveryDay
    // }
    formData.deliveryDay = result.deliveryDay
    formData.replyMessage = result.replyMessage
  }
}
onLoad(async (options) => {
  if (options?.id) {
    detailId.value = options?.id
    await getProductDetail()
  } else {
    uni.reLaunch({
      url: '/pages/notify/index'
    })
  }
})
</script>
<style scoped lang="scss">
.oem-box {
  box-sizing: border-box;
  min-height: 80rpx;
  border: 1px solid #D1D5DB;
  border-radius: 8rpx;
  vertical-align: middle;
  padding: 10rpx;
}

.swiper-icon {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 5rpx;

  .u-icon {
    margin-top: -10rpx;
    color: #fff
  }
}
</style>
